﻿using Api.FilesManage.App_Start;
using Common.Library;
using Common.Model;
using Document.Library;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Api.FilesManage.Areas.Files.Controllers
{

    /// <summary>
    /// 公用操作接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "Files")]
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : BaseApiController
    {       
        /// <summary>
        /// 构造函数
        /// </summary>
        public FilesController()
        {

        }

        #region Image文件夹受UploadFolderType枚举限制【对外使用-Base64方式】
        /// <summary>
        /// 上传图片【并删除原始图片】-服务名称文件夹路径枚举限制
        /// </summary>
        /// <param name="inputInfo">图片上传请求实体</param>
        /// <returns></returns>
        [HttpPost("UploadImage")]
        public ResultJsonInfo<FilesInfo> UploadImage([FromBody]ImageUploadInfo inputInfo)
        {
            var resultInfo = new ResultJsonInfo<FilesInfo>();

            TryCatch(() =>
            {
                if (!string.IsNullOrEmpty(inputInfo.originalName))
                {

                    inputInfo.uploadFolder = inputInfo.servicePath.ToString() + "/" + inputInfo.uploadFolder;

                    ImageHelper.RemoveImage(inputInfo.originalName, inputInfo.uploadFolder.ToString());
                }

                var fileInfo = ImageHelper.SaveBase64Image(inputInfo.imageBase64, inputInfo.uploadFolder.ToString());

                resultInfo.Data = fileInfo;
                resultInfo.Code = ActionCodes.Success;

            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "上传图片失败");

            }, $"系统错误，上传图片失败");
            return resultInfo;
        }

        /// <summary>
        /// 上传图片【不删除原始图片】-服务名称文件夹路径枚举限制
        /// </summary>
        /// <param name="inputInfo">图片上传请求实体</param>
        /// <returns></returns>
        [HttpPost("UploadImageNoRemove")]
        public ResultJsonInfo<FilesInfo> UploadImageN([FromBody]ImageUploadInfo inputInfo)
        {
            var resultInfo = new ResultJsonInfo<FilesInfo>();

            TryCatch(() =>
            {
                inputInfo.uploadFolder = inputInfo.servicePath.ToString() + "/" + inputInfo.uploadFolder;

                var fileInfo = ImageHelper.SaveBase64Image(inputInfo.imageBase64, inputInfo.uploadFolder.ToString());
                resultInfo.Data = fileInfo;
                resultInfo.Code = ActionCodes.Success;

            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "上传图片失败");

            }, $"系统错误，上传图片失败");
            return resultInfo;
        }

        /// <summary>
        /// 根据文件路径，删除图片文件-文件夹受UploadFolderType枚举限制
        /// </summary>
        /// <param name="inputInfo">文件Info</param>
        /// <returns></returns>
        [HttpPost("RemoveImage")]
        public ResultJsonInfo<bool> RemoveImage([FromBody]ImageUploadInfo inputInfo)
        {
            var resultInfo = new ResultJsonInfo<bool>();

            TryCatch(() =>
            {
                if (!string.IsNullOrEmpty(inputInfo.originalName))
                {
                    inputInfo.uploadFolder = inputInfo.servicePath.ToString() + "/" + inputInfo.uploadFolder;

                    resultInfo.Data = ImageHelper.RemoveImage(inputInfo.originalName, inputInfo.uploadFolder.ToString());
                    resultInfo.Code = ActionCodes.Success;
                }
            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "删除文件失败");

            }, $"系统错误，删除文件失败");
            return resultInfo;
        }

        #endregion

        #region 分片文件上传

        /// <summary>
        /// 上传文件信息(分片上传)
        /// </summary>
        /// <returns></returns>
        [HttpPost("SaveFiles")]
        public async Task<IActionResult> SaveFiles()
        {
            return await Task.Run(() =>
            {
                var resultInfo = new ResultJsonInfo<string>();
                var files = Request.Form.Files;
                long size = files.Sum(f => f.Length);
                TryCatch(() =>
                {
                    foreach (var formFile in files)
                    {
                        if (formFile.Length > 0)
                        {
                            var name = Request.Form["chunk"].ToString()==""?"0": Request.Form["chunk"].ToString();
                            var folderPath = Request.Form["folderPath"].ToString();
                            var servicePath = Request.Form["servicePath"].ToString();
                            if (!string.IsNullOrEmpty(servicePath))
                            {
                                folderPath= servicePath + "/"+ folderPath;
                            }
                            var temp_path = Request.Form["guid"].ToString();
                            using (var ms = new MemoryStream())
                            {
                                formFile.CopyTo(ms);
                                var fileBytes = ms.ToArray();
                                FileHelper.SaveFile(fileBytes, folderPath, temp_path, name);
                            }
                        }
                    }
                }, ex =>
                {
                    resultInfo.SystemExc(resultInfo, ex, "上传图片失败");

                }, $"系统错误，上传图片失败");

                return Ok(new { count = files.Count, size });
            });
        }

        /// <summary>
        /// 合并文件信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("MergeFiles")]
        public ResultJsonInfo<FilesInfo> MergeFiles([FromBody]FilesModifyInfo fileInfo)
        {
            var resultInfo = new ResultJsonInfo<FilesInfo>();

            TryCatch(() =>
            {
                fileInfo.folderPath = fileInfo.servicePath.ToString() + "/" + fileInfo.folderPath;

                resultInfo.Data = FileHelper.FileMerge(fileInfo.folderPath, fileInfo.temp_path, fileInfo.media_sub_type);
                resultInfo.Msg = "合并成功！";
                resultInfo.Code = ActionCodes.Success;

            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "合并文件信息失败");

            }, $"系统错误，合并文件信息失败");

            return resultInfo;
        }

        #endregion


        /// <summary>
        /// 上传文件信息（文件为二进制数据）
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadFiles")]
        public ResultJsonInfo<string> UploadFiles([FromBody]FilesModifyInfo fileInfo)
        {
            var resultInfo = new ResultJsonInfo<string>();
            TryCatch(() =>
            {

                fileInfo.folderPath = fileInfo.servicePath.ToString() + "/" + fileInfo.folderPath;
                fileInfo.name = GuidHelper.GetGuid() + fileInfo.name.Substring(fileInfo.name.IndexOf("."));
                resultInfo.Data = FileHelper.SaveFile(fileInfo.fileByte, fileInfo.folderPath, fileInfo.temp_path, fileInfo.name);
                resultInfo.Code = ActionCodes.Success;

            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "上传文件信息失败");

            }, $"系统错误，上传文件信息失败");

            return resultInfo;
        }

        /// <summary>
        /// 文件转码信息
        /// </summary>
        /// <param name="folderPath">业务文件夹</param>
        /// <param name="sourceFile"></param>
        /// <param name="targetFile"></param>
        /// <returns></returns>
        [HttpGet("EscapeFiles/{folderPath}/{sourceFile}/{targetFile}")]
        public ResultJsonInfo<FilesInfo> EscapeFiles(string folderPath, string sourceFile, string targetFile)
        {
            var resultInfo = new ResultJsonInfo<FilesInfo>();

            TryCatch(() =>
            {
                Task.Run(()=> {

                    VideoRecodeData videoRecodeData = new VideoRecodeData
                    {
                        BasePath = folderPath,
                        SourceFile = sourceFile,//源文件
                        TargetFile = targetFile,//转换后的文件
                        removeSourceFile=true
                    };
                    VideoRecodeHelper _convert = new VideoRecodeHelper(videoRecodeData);
                    _convert.Start();
                });
                resultInfo.Msg = "开启文件转码成功！";
                resultInfo.Code = ActionCodes.Success;

            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "文件转码失败");

            }, $"系统错误，文件转码失败");

            return resultInfo;
        }


        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="folderPath">业务文件夹</param>
        /// <param name="sourceFile">文件名</param>
        /// <returns></returns>
        [HttpGet("ExistFile")]
        public ResultJsonInfo<bool> ExistFile(string folderPath, string sourceFile)
        {
            var resultInfo = new ResultJsonInfo<bool>();

            TryCatch(() =>
            {
                sourceFile= sourceFile.Substring(0, sourceFile.IndexOf(".") + 1);
                var exist = FileHelper.ExistFile(folderPath, sourceFile+"avi")|| FileHelper.ExistFile(folderPath, sourceFile + "mpg");
                if (exist)
                {
                    resultInfo.Data = exist;
                    resultInfo.Msg = "文件转码中！";
                }
                else
                {
                    resultInfo.Data = exist;
                    resultInfo.Msg = "文件转码完成！";
                    resultInfo.Code = ActionCodes.Success;
                }
            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "删除文件失败");

            }, $"系统错误，删除文件失败");
            return resultInfo;
        }


        /// <summary>
        /// 根据文件路径，删除文件
        /// </summary>
        /// <param name="fileName">文件地址信息</param>
        /// <returns></returns>
        [HttpGet("RemoveFile/{fileName}")]
        public ResultJsonInfo<bool> RemoveFile(string fileName)
        {
            var resultInfo = new ResultJsonInfo<bool>();

            TryCatch(() =>
            {
                if (!string.IsNullOrEmpty(fileName))
                {
                    resultInfo.Data = FileHelper.FileRemove(fileName);
                    resultInfo.Code = ActionCodes.Success;
                }
            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "删除文件失败");

            }, $"系统错误，删除文件失败");
            return resultInfo;
        }


        /// <summary>
        /// 批量删除文件
        /// </summary>
        /// <param name="fileNames">文件列表信息</param>
        /// <returns></returns>
        [HttpPost("RemoveFiles")]
        public ResultJsonInfo<bool> RemoveFiles(List<string> fileNames)
        {
            var resultInfo = new ResultJsonInfo<bool>();

            TryCatch(() =>
            {
                if (fileNames.Count>0)
                {
                    Task.Run(()=> {
                        foreach (var item in fileNames)
                        {
                            FileHelper.FileRemove(item);
                        }
                    });
                    resultInfo.Data = true;
                    resultInfo.Code = ActionCodes.Success;
                }
            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "删除文件失败");

            }, $"系统错误，删除文件失败");
            return resultInfo;
        }


    }
}